<template>
  <div class="census-manage">
    <basic-container>
      <avue-crud
        :table-loading="loading"
        ref="crud"
        :option="option"
        :data="data"
        :page.sync="page"
        @on-load="onLoad"
        :search.sync="search"
        @selection-change="selectionChange"
        @refresh-change="onLoad"
        @row-save="rowSave"
        @search-change="searchChange"
        @row-update="rowUpdate"
        @row-del="rowDel"
        v-model="item"
      >
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            @click="deleteInfo"
            v-if="power"
            >删 除
          </el-button>
        </template>
        <template slot-scope="{ type, size, row, index }" slot="menu">
          <el-button
            v-if="row.status == 0 && role !== '任课老师'"
            icon="el-icon-edit"
            :size="size"
            :type="type"
            @click="editorInfo(row, index)"
            >编 辑</el-button
          >
          <el-button
            v-if="row.status == 0 && role !== '任课老师'"
            icon="el-icon-delete"
            :size="size"
            :type="type"
            @click="rowDel(row)"
            >删 除</el-button
          >
          <el-button
            v-if="row.status == 0"
            icon="el-icon-share"
            :size="size"
            :type="type"
            @click="releaseProject(row)"
            >上 架</el-button
          >
          <el-button
            v-if="row.status == 1"
            icon="el-icon-share"
            :size="size"
            :type="type"
            @click="unProject(row)"
            >下 架</el-button
          >
          <el-button
            v-if="row.status == 0 && role !== '任课老师'"
            icon="el-icon-check"
            :size="size"
            :type="type"
            @click="goToCustomList(row)"
            >自定义设置</el-button
          >
          <el-button
            v-if="row.status == 0"
            icon="el-icon-check"
            :size="size"
            :type="type"
            @click="goToBindList(row)"
            >绑定人群</el-button
          >
          <el-button
            icon="el-icon-view"
            :size="size"
            :type="type"
            @click="getViewByProject(row)"
            >查 看</el-button
          >
          <el-button
            v-if="row.status == 1 && schoolType == 9"
            icon="el-icon-view"
            :size="size"
            :type="type"
            @click="getQrcode(row)"
          >
            查看二维码
          </el-button>
        </template>
        <template slot="accessRemarkForm">
          <el-row>
            <tinymce-editor
              v-model="accessRemark"
              ref="editor"
            ></tinymce-editor>
          </el-row>
        </template>

        <template slot-scope="scope" slot="accessRemark">
          <span>{{ scope.row.accessRemark }}</span>
        </template>

        <!-- <template slot="guidanceNoteForm">
          <el-row>
            <tinymce-editor
              v-model="guidanceNote"
              ref="editor"
            ></tinymce-editor>
          </el-row>
        </template> -->
      </avue-crud>
    </basic-container>
    <el-dialog
      title="普查题目列表"
      :visible.sync="answerDetailDialogView"
      class="dialogInfoCss"
    >
      <div class="container">
        <answerDetailDialog :answerData="answerData"></answerDetailDialog>
      </div>
    </el-dialog>
    <el-dialog
      :title="title"
      :visible.sync="codeDialogView"
      class="dialogInfoCss"
      width="30%"
      center
      v-if="codeDialogView"
    >
      <div class="code">
        <img :src="codeData.codeUrl" alt="" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="diwnLoadCode">下载二维码</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCensusList,
  saveCensus,
  updateCensus,
  deleteCensus,
  releaseProject,
  getViewByProjectId,
} from "@/api/census";
import TinymceEditor from "../../components/tinymce-editor/tinymce-editor";
import { getList } from "@/api/grade/main.js";
import { getTermListAll } from "@/api/system/semester";
import { getInfo } from "@/api/system/info.js";
import answerDetailDialog from "./answerDetailDialog";
import QRCode from "qrcode";
import { mapGetters } from "vuex";
export default {
  name: "CensusManage",
  components: { TinymceEditor, answerDetailDialog },
  data() {
    return {
      teamReport: false,
      item: {},
      user: {},
      search: {},
      answerData: [],
      sampleParams: {},
      projectId: "",
      answerDetailDialogView: false,
      selectionList: [],
      promote: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
      },
      option: {
        // addBtnText: '添加类别',
        delBtnText: "删除",
        excelBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        border: true,
        selection: true,
        index: true,
        expandLevel: 3,
        headerAlign: "left",
        align: "left",
        tree: false,
        labelWidth: 120,
        menuWidth: 300,
        column: [
          {
            label: "普查名称",
            overHidden: true,
            searchLabelWidth: 120,
            prop: "projectName",
            formslot: true,
            searchSpan: 8,
            search: true,
            order: 1,
            rules: [
              {
                required: true,
                message: "请输入普查名称",
                trigger: "click",
              },
            ],
          },
          {
            label: "适用学期",
            prop: "termId",
            searchSpan: 8,
            search: true,
            overHidden: true,
            searchLabelWidth: 120,
            order: 2,
            type: "select",
            props: {
              label: "term",
              value: "termId",
            },
            dicUrl: "/api/blade-measure/measure/term/listAll",
            rules: [
              {
                required: true,
                message: "请选择适用学期",
                trigger: "click",
              },
            ],
          },
          {
            label: "适用人群",
            prop: "grade",
            type: "checkbox",
            searchSpan: 8,
            search: true,
            overHidden: true,
            searchLabelWidth: 120,
            order: 2,
            span: 24,
            props: {
              label: "gradeName",
              value: "gradeNo",
            },
            dicUrl: `/api/blade-system/grade/list`,
          },
          {
            label: "测量类别",
            prop: "gaugeTypeId",
            overHidden: true,
            order: 4,
            searchLabelWidth: 120,
            searchSpan: 8,
            search: true,
            type: "select",
            props: {
              label: "typeName",
              value: "projectGaugeTypeId",
            },
            dicUrl: "/api/blade-measure/measure/projectgaugetype/query",
            rules: [
              {
                required: true,
                message: "请选择测量类别",
                trigger: "click",
              },
            ],
          },
          {
            label: "测评完成日期",
            type: "date",
            searchSpan: 8,
            search: true,
            searchLabelWidth: 120,
            prop: "requestDate",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            order: 4,
            rules: [
              {
                required: true,
                message: "请输测评完成日期",
                trigger: "blur",
              },
            ],
          },
          {
            label: "测评指导语",
            span: 24,
            order: 4,
            overHidden: true,
            prop: "accessRemark",
            formslot: true,
            rules: [
              {
                required: true,
                message: "请输入测评指导语",
                trigger: "click",
              },
            ],
          },
          {
            label: "测验说明",
            span: 24,
            order: 5,
            hide: true,
            prop: "remark",
            type: "textarea",
            rules: [
              {
                required: true,
                message: "请输入测验说明",
                trigger: "click",
              },
            ],
          },
          {
            label: "价格",
            order: 6,
            prop: "price",
            type: "input",
            hide: this.hidePrice(),
            addDisplay: this.hidePriceForm(),
            editDisplay: this.hidePriceForm(),
            rules: [],
          },
          {
            label: "测评理论",
            span: 24,
            hide: true,
            prop: "guidanceNote",
          },
          {
            label: "发布状态",
            span: 24,
            prop: "status",
            type: "select",
            searchLabelWidth: 120,
            searchSpan: 8,
            search: true,
            addDisplay: false,
            editDisplay: false,
            dicData: [
              {
                label: "已上架",
                value: 1,
              },
              {
                label: "待上架",
                value: 0,
              },
            ],
          },
          {
            label: "项目图片",
            type: "upload",
            listType: "picture-img",
            propsHttp: {
              res: "data",
              url: "fileUrl",
            },
            canvasOption: {
              text: " ",
              ratio: 0.1,
            },
            action: "/api/blade-file/file/uploadFile",
            tip: "只能上传jpg/png用户头像，且不超过500kb，文件名称汉字不能少于2个字!",
            span: 24,
            row: true,
            prop: "classesName",
          },
        ],
      },
      data: [],
      guidanceNote: "",
      loading: true,
      gradeNameList: [],
      termListAll: [],
      accessRemark: "",
      power: false,
      role: "",
      codeDialogView: false,
      codeData: {
        projectId: "",
        codeUrl: "",
        projectName: "",
      },
      title: "",
      schoolTenant: {},
      deptId: "",
      postId: "",
      roleId: "",
    };
  },
  mounted() {
    // let guidanceNote = ""; // 请求后台返回的内容字符串
    // this.str = this.escapeStringHTML(guidanceNote);
    let accessRemark = "";
    this.str = this.escapeStringHTML(accessRemark);

    let role = JSON.parse(localStorage.getItem("saber-userInfo")).content
      .authority;
    role == "任课老师" ? (this.power = false) : (this.power = true);
    this.role = role;
  },
  watch: {
    accessRemark: {
      handler(val) {
        //监听指导语数据变化，否则过不了校验
        this.item.accessRemark = val;
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(["userInfo"]),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.projectId);
      });
      return ids.join(",");
    },
    schoolType() {
      return this.userInfo.schoolType;
    },
  },
  created() {
    this.onLoad();
    getList().then((res) => {
      this.gradeNameList = res.data.data;
    });
    getTermListAll().then((res) => {
      this.termListAll = res.data.data;
    });
    this.getTenantInfo();
  },
  methods: {
    async onLoad(page = this.page, params = this.search) {
      if (window.localStorage.getItem("saber-userInfo")) {
        params.tenantId = JSON.parse(
          window.localStorage.getItem("saber-userInfo")
        ).content.tenantId;
      }
      //模拟分页
      // this.page.total = 40;
      const {
        data: { data },
      } = await getCensusList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      );
      data.records.map((rowData) => {
        rowData.grade = rowData.gradId.split(",");
        rowData.requestDate = rowData.requestDate.split(" ")[0] || "";
      });
      this.loading = false;
      this.data = data.records;
      // console.log(this.data);
      this.page.total = data.total;
    },
    async rowSave(form, done) {
      if (!form.status) {
        form.status = 0;
      }
      // console.log(form.grade);
      form.accessRemark = this.accessRemark;
      // form.guidanceNote = this.guidanceNote;
      form.requestDate = form.requestDate + " 23:59:59";
      form.gradId = form.grade
        .sort((a, b) => {
          return a - b;
        })
        .join(",");
      let gradeNames = form.$grade.split(" | ");
      form.gradName = this.filterGradeName(gradeNames).join(",");
      this.termListAll.map((item) => {
        if (item.termId == form.termId) {
          form.term = item.term;
          form.half = item.half;
          form.yearly = item.yearly;
        }
      });
      await saveCensus(form);

      this.onLoad();

      done(form);
    },
    async searchChange(params, done) {
      await this.onLoad(this.page, params);
      done();
    },
    async rowUpdate(form, index, done) {
      form.gradId = form.grade
        .sort((a, b) => {
          return a - b;
        })
        .join(",");
      let gradeNames = form.$grade.split(" | ");
      form.gradName = this.filterGradeName(gradeNames).join(",");
      // gradeNames.join(",");
      form.requestDate = form.requestDate + " 23:59:59";
      // form.guidanceNote = this.guidanceNote;
      form.accessRemark = this.accessRemark;
      this.termListAll.map((item) => {
        if (item.termId == form.termId) {
          form.term = item.term;
          form.half = item.half;
          form.yearly = item.yearly;
        }
      });
      await updateCensus(form);
      this.onLoad();

      done(form);
    },
    //过滤年级名称
    filterGradeName(list) {
      let gradeList = [];
      this.gradeNameList.forEach((item) => {
        list.forEach((item2) => {
          if (item.gradeName == item2) gradeList.push(item2);
        });
      });
      return gradeList;
      // console.log(gradeList);
    },
    async rowDel(form) {
      this.$confirm("此操作将永久删除此测评项目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteCensus({ ids: form.projectId });
          this.onLoad(this.page);
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        });
    },
    async deleteInfo() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          return deleteCensus({ ids: this.ids });
        })
        .then(() => {
          this.loading = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    getViewByProject(row) {
      this.answerData = [];
      getViewByProjectId({ projectId: row.projectId }).then((result) => {
        if (result.data.code == "200") {
          if (result.data.data.length) {
            this.answerData = result.data.data;
            this.answerDetailDialogView = true;
          } else {
            this.$message.warning("没有可以查看的题目！");
          }
        }
      });
    },
    getTenantInfo() {
      getInfo().then((res) => {
        this.schoolTenant = res.data.data;
        let deptId =
          (this.schoolTenant.dept &&
            this.schoolTenant.dept.filter((item) => {
              return item.deptName == "年级部" || item.deptName == "企业部门";
            })[0].id) ||
          "";
        let roleId =
          (this.schoolTenant.role &&
            this.schoolTenant.role.filter((item) => {
              return item.roleName == "学生" || item.roleName == "员工";
            })[0].id) ||
          "";
        let postId =
          (this.schoolTenant.post &&
            this.schoolTenant.post.filter((item) => {
              return item.postName == "学生" || item.postName == "员工";
            })[0].id) ||
          "";
        this.deptId = deptId;
        this.postId = postId;
        this.roleId = roleId;
      });
    },
    getQrcode(row) {
      this.codeDialogView = true;
      this.codeData.projectName = row.projectName;
      this.title = row.projectName;
      let tenantId =
        this.schoolTenant.role && this.schoolTenant.role[0].tenantId;
      let http = "https://www.hongkangxinli.cn/xlmobile/#/login";
      let url = `${http}?projectId=${row.projectId}&deptId=${this.deptId}&roleId=${this.roleId}&postId=${this.postId}&tenantId=${tenantId}&type=code`;
      let opts = {
        errorCorrectionLevel: "L",
        type: "image/png",
        quality: 0.5,
        margin: 2,
        width: 140,
        height: 140,
        text: `${http}?projectId=${row.projectId}&deptId=${this.deptId}&roleId=${this.roleId}&postId=${this.postId}&tenantId=${tenantId}&type=code`,
        color: {
          dark: "#000000",
          light: "#fff",
        },
      };
      this.$nextTick(() => {
        console.log(url);
        QRCode.toDataURL(url, opts, (error, url) => {
          if (error) return console.log(error);
          this.codeData.codeUrl = url;
        });
      });
    },
    diwnLoadCode() {
      let a = document.createElement("a");
      a.href = this.codeData.codeUrl;
      a.download = `${this.codeData.projectName}.png`;
      a.click();
    },
    editorInfo(row, index) {
      // this.guidanceNote = row.guidanceNote;
      this.accessRemark = row.accessRemark;
      this.$refs.crud.rowEdit(row, index);
    },
    releaseProject(row) {
      this.loading = true;
      releaseProject({ projectId: row.projectId, price: row.price }).then(
        () => {
          this.onLoad(this.page);
          this.loading = false;
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        }
      );
    },
    unProject(row) {
      this.loading = true;
      row.status = 0;
      row.requestDate = "";
      updateCensus(row).then(() => {
        this.onLoad(this.page);
        this.loading = false;
        this.$message({
          type: "success",
          message: "操作成功!",
        });
        this.$refs.crud.toggleSelection();
      });
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    goToCustomList(row) {
      this.$router.push({
        name: "自定义设置",
        query: { projectId: row.projectId },
      });
    },
    goToResultSet() {
      this.$router.push({ name: "结果列表" });
    },
    goToBindList(row) {
      let tenantId = "";
      if (window.localStorage.getItem("saber-userInfo")) {
        tenantId = JSON.parse(window.localStorage.getItem("saber-userInfo"))
          .content.tenantId;
      }
      this.$router.push({
        name: "绑定人群",
        query: {
          projectId: row.projectId,
          projectName: row.projectName,
          gradeIds: row.gradId,
          tenantId: tenantId,
        },
      });
    },
    escapeStringHTML(str) {
      //把实体格式字符串转义成HTML格式的字符串
      str = str.replace(/&lt;/g, "<");
      str = str.replace(/&gt;/g, ">");
      return str;
    },
    hidePrice() {
      const type =
        this.schoolType ||
        JSON.parse(localStorage.getItem("saber-userInfo")).content.schoolType ||
        "";
      if (type != "9") {
        return true;
      } else {
        return false;
      }
    },
    hidePriceForm() {
      const type =
        this.schoolType ||
        JSON.parse(localStorage.getItem("saber-userInfo")).content.schoolType ||
        "";
      if (type == "9") {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.census-manage {
  .container {
    height: 70vh;
    overflow-y: auto;
  }
  .dialogInfoCss {
    overflow-y: hidden;
    margin-top: -50px;
    // margin-bottom: 40px;
  }

  .code {
    text-align: center;
    height: 20vh;
    min-height: 160px;
  }
}
</style>
